package com.lean.android.projecttemplate.ui

import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.navigation.NavController
import androidx.navigation.NavDestination
import androidx.navigation.NavGraph
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController

@Stable
class AppState(val navController: NavController) {

    private val topLevelRoutes = TopLevelDestination.entries.map { it.route }

    val shouldShowBottomBar: Boolean
        @Composable get() = navController.currentBackStackEntryAsState().value?.destination?.route in topLevelRoutes

    val currentRouteState: String? //只有从state中取Compose才会进行监听
        @Composable get() = navController.currentBackStackEntryAsState().value?.destination?.route

    val currentRoute: String?
        get() = navController.currentDestination?.route

    fun navigateToTopDestination(topLevelDestination: TopLevelDestination) {
        if (currentRoute != topLevelDestination.route) {
            navController.navigate(topLevelDestination.route) {
                launchSingleTop = true
                restoreState = true
                popUpTo(findStartDestination(navController.graph).id) {
                    saveState = true
                }
            }
        }
    }

    fun navigateUp() {
        navController.navigateUp()
    }

    private val NavGraph.startDestination: NavDestination?
        get() = findNode(startDestinationId)

    private tailrec fun findStartDestination(destination: NavDestination): NavDestination {
        return if (destination is NavGraph) findStartDestination(destination.startDestination!!) else destination
    }

}

@Composable
fun rememberAppState(navController: NavController = rememberNavController()): AppState {
    return remember(navController) {
        AppState(navController)
    }
}